// pages/yoshop/user/index.js

let _this;
let Bmob = require('../../utils/bmob.js');
let common = require('../../utils/common.js');
let App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userName: '',
    userPwd: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: '登录',
    })

    _this = this;
    Bmob.initialize("8bbd2fa87eece23337234b59c300fb2e", "0422786c4a1502011b37da0d9f437770");

  },

  bindGetUserInfo(e) {
    console.log(e.detail.userInfo)
  },

  getOpenId: function(success) {
    //获取open id，请在官网填写微信小程序key
    wx.login({
      success: function(res) {
        if (res.code) {
          //发起网络请求
          console.log(res.code);

          Bmob.User.requestOpenId(res.code, {
            success: function(result) {
              _this.setData({
                loading: true,
                openId: result.openid
              })
              console.log(result)
              success&&success()
            },
            error: function(error) {
              // Show the error message somewhere
              console.log("Error: " + error.code + " " + error.message);
            }
          });

        } else {
          console.log('获取用户登录态失败！' + res.errMsg);
          //common.showTip('获取用户登录态失败！', 'loading');
        }
      }
    });
  },

  /**
   *  获取用户名
   */
  getUserName: function(e) {
    _this.setData({
      userName: e.detail.value
    });
  },

  /**
   * 获取密码
   */
  getPassword: function(e) {
    _this.setData({
      userPwd: e.detail.value
    });
  },

  /**
   * 登录
   */
  login: function() {
    // wx.showLoading({
    //   title: '正在登录',
    //   mask: true
    // })
    App._get(
      'login', {
        username: _this.data.userName,
        password: _this.data.userPwd
      },
      function(res) {
        if (res.hasOwnProperty('code')) {
          if (res.code === 109) {
            App.showError('请填写用户名和密码');
            return false;
          }
          if (res.code === 101) {
            App.showError('用户名或密码不正确');
            return false;
          }

          App.showError('服务发生问题');
          return false;
        }

        wx.setStorageSync('userName', _this.data.userName);
        wx.setStorageSync('bmobObjectId', res.objectId);
        wx.setStorageSync('bmobSessionToken', res.sessionToken);
        wx.setStorageSync('profileId', res.profile.objectId)

        console.log(res);

        if (!res.hasOwnProperty('miniOpenId') || res.miniOpenId === '') {
          //绑定微信
          console.log('绑定微信:' + wx.getStorageSync('userName'));
          _this.getOpenId(function(){
            _this.bindMiniOpenId(res.objectId)
            wx.navigateBack()
          });
           
        }
        wx.navigateBack()

      }
      , false
      , function () {
        //wx.hideLoading()
      }
      );
  },

  /**
   * 绑定帐户微信
   */
  bindMiniOpenId: function(objectId){
    App._put(
      'users/' + objectId,
      wx.getStorageSync('bmobSessionToken'), {
        miniOpenId: _this.data.openId
      },
      function (res) {
        console.log(res);
      });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  }
})